<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script id="myWorker"  type="text/worker">
self.onmessage = function(e) {
  var offscreenCanvas = new OffscreenCanvas(4, 4);
  var ctx = offscreenCanvas.getContext("2d");
  ctx.fillStyle = "#FF0102";
  ctx.fillRect(0, 0, 4, 4);

  offscreenCanvas.convertToBlob().then(function(blob) {
    self.postMessage(blob);
  });

};
</script>
<script type = 'text/javascript'>
// In blink Layout Tests, flag "--enable-threaded-compositing", which is
// essential for idle task running, is not turned on by default. This makes
// it convenient to test the case when CanvasAsyncBlobCreator is idling for
// too long and switching to forcing encoding in a normal task.
// Passing this test means that the enforcing mechanism in
// CanvasAsyncBlobCreator for OffscreenCanvas case is working as expected.
var w = 4;
var h = 4;

var newImg = new Image();
function imageLoaded() {
    var canvas2 = document.createElement("canvas");
    canvas2.width = w;
    canvas2.height = h;
    var ctx2 = canvas2.getContext("2d");
    ctx2.drawImage(newImg, 0, 0, w, h);

    var imageData = ctx2.getImageData(0, 0, w, h).data;
    assert_equals(imageData[0], 255);
    assert_equals(imageData[1], 1);
    assert_equals(imageData[2], 2);
    assert_equals(imageData[3], 255);
    testImageFromOffscreen.done();
}

var workerBlob = new Blob([document.getElementById('myWorker').textContent]);
var worker = new Worker(URL.createObjectURL(workerBlob));
worker.addEventListener("message", function(msg) {
    var blob = msg.data;
    newImg.src = URL.createObjectURL(blob);
});

var testImageFromOffscreen = async_test(
    "Check if the image loaded from blob returned by " +
    "OffscreenCanvas.convertToBlob() have expected image data values.");

testImageFromOffscreen.step(function() {
  newImg.onload = testImageFromOffscreen.step_func(imageLoaded);
  worker.postMessage("");
});

</script>
